package com.hanbang.gycatering.property;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.RepairBeanData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.myviews.MyDialog;
import com.hanbang.gycatering.myviews.MyDialog.MODE;
import com.hanbang.gycatering.myviews.MyDialog.OnClickCallback;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MyToast;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class PropertyFix extends BaseActivity implements OnClickListener {
	// private boolean isShowDelete=false;
	private GridView noScrollgridview;
	private TextView mTView, submit_save;
	private LinearLayout mBtnDropDown;
	private GridAdapter adapter;
	private EditText fix_describe;
	private String tempPath = "";
	private int repairId = 0;
	private ArrayList<String> listDatas = new ArrayList<String>();
	private ArrayList<Object> repairsList = new ArrayList<Object>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(savedInstanceState!=null){
			MyLog.e("hehehe", savedInstanceState.getString("123"));
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.propertyfix);
		initView();
		setTheclick();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("123", "123");
		super.onSaveInstanceState(outState);
	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) findViewById(R.id.top_bar_title)).setText("报修申请");
		submit_save = (TextView) findViewById(R.id.submit_save);
		fix_describe = (EditText) findViewById(R.id.fix_describe);
		// 下拉框
		mTView = (TextView) findViewById(R.id.tv_value);
		mBtnDropDown = (LinearLayout) findViewById(R.id.bt_dropdown);
		// 要上传图片gridview
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		// 获得报修类别
		getrepairs();
		initGridView();
	}

	private void getrepairs() {
		// TODO Auto-generated method stub
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.repairs,
				new MyRequestCallBack<String>(PropertyFix.this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								JSONArray infor = json.getJSONArray("info");
								for (int i = 0; i < infor.length(); i++) {
									RepairBeanData repair = new RepairBeanData();
									repair.setId(infor.getJSONObject(i).getInt(
											"id"));
									repair.setName(infor.getJSONObject(i)
											.getString("name"));
									repairsList.add(repair);
								}

							} else {
								MyToast.show(PropertyFix.this, "获取数据失败",
										Toast.LENGTH_SHORT);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(PropertyFix.this, "获取数据失败",
									Toast.LENGTH_SHORT);
						}
					}
				});
	}

	private void initGridView() {
		// TODO Auto-generated method stub
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		noScrollgridview.setAdapter(adapter);

		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == listDatas.size()) {
					MyDialog dialog = new MyDialog(PropertyFix.this,
							R.style.about_me_dialog, MODE.HEAD);
					dialog.setOnClickCallback(new OnClickCallback() {

						@Override
						public void onClick(MyDialog dialog, Object number,
								Object content) {
							if ((Integer) number == 1) {
								photo();
							} else if ((Integer) number == 2) {
								// 获取相册
								Intent intent2 = new Intent();
								intent2.setDataAndType(
										MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
										"image/*");
								intent2.setAction(Intent.ACTION_PICK);
								intent2.putExtra("return-data", true);
								startActivityForResult(intent2, 777);
							} else if ((Integer) number == 3) {

							}
						}
					});
					dialog.show();
				} else {

				}
			}
		});
	}

	public void photo() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			File dir = new File(MyApplication.cameraPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir,
					String.valueOf(System.currentTimeMillis()) + ".jpg");
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
			tempPath = file.getPath();
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
			startActivityForResult(intent, 30);
		} else {
			MyToast.show(PropertyFix.this, "没有储存卡", 1000);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		// 拍照
		case 30:
			if (resultCode == -1) {
				if (!"".equals(tempPath)) {
					MyLog.e("onActivityResult", tempPath + "");
					File file = new File(tempPath);
					if (file.length() > 0) {
						MyLog.e("onActivityResult", listDatas.size() + "");
						listDatas.add(tempPath);
						MyLog.e("onActivityResult", listDatas.size() + "");
						// isShowDelete=false;
						adapter.notifyDataSetChanged();
					}
					tempPath = "";
				}
			}
			break;
		// 相册
		case 777:
			boolean flagexist = false;
			if (resultCode == -1) {
				Uri url = data.getData();
				String photopath = getPath(PropertyFix.this, url);
				for (String element : listDatas) {
					if (element.equals(photopath)) {
						flagexist = true;
					}

				}
				if (flagexist) {
					MyToast.show(PropertyFix.this, "图片已存在，请重新选择",
							Toast.LENGTH_SHORT);
				} else {
					File file = new File(MyApplication.cameraPath,
							String.valueOf(System.currentTimeMillis()) + ".jpg");
					listDatas.add(photopath);
					adapter.notifyDataSetChanged();
				}
			}
			break;
		default:
			break;
		}
	}

	private void setTheclick() {
		// TODO Auto-generated method stub
		mBtnDropDown.setOnClickListener(this);
		submit_save.setOnClickListener(this);
		setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.bt_dropdown:
			MyDialog dialog = new MyDialog(PropertyFix.this,
					R.style.about_me_dialog, MODE.SELECT) {
			};
			dialog.setTitle("选择报修类别");
			dialog.setOnClickCallback(new OnClickCallback() {
				@Override
				public void onClick(MyDialog dialog, Object number,
						Object content) {
					if ("-1".equals(String.valueOf(number))) {
						mTView.setText(String.valueOf("请选择类别"));
					} else {
						mTView.setText(((RepairBeanData) repairsList
								.get((Integer) number)).getName());
						repairId = ((RepairBeanData) repairsList
								.get((Integer) number)).getId();
					}

				}
			});
			dialog.setSelectData(repairsList);
			dialog.show();
			break;
		case R.id.submit_save:
			if ("请选择类别".equals(mTView.getText())) {
				MyToast.show(PropertyFix.this, "请选择报修类别", Toast.LENGTH_SHORT);
				break;
			}
			if ("".equals(fix_describe.getText().toString().trim())) {
				MyToast.show(PropertyFix.this, "请选填写报修描述", Toast.LENGTH_SHORT);
				break;
			}
			// 上传数据
			submitData(listDatas, repairId, fix_describe.getText().toString()
					.trim());
			// 删除照片文件夹
			break;
		default:
			break;
		}
	}

	private void submitData(ArrayList<String> list, int id, String content) {
		MyLog.e("submitData", "http: // gangyucanyin.hbung.com/API.ashx?"
				+ "action=addrepairs&userphone=15527258455"
				+ "&password=123456&CategoryId=" + id + "&RepairsContent="
				+ content);
		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "addrepairs");
		params.addBodyParameter("userphone", userData.getUserphone());
		params.addBodyParameter("password", userData.getUserpassword());
		params.addBodyParameter("CategoryId", id + "");
		params.addBodyParameter("RepairsContent", content);
		String[] filename = { "Filedataone", "Filedatatwo", "Filedatathree" };
		for (int i = 0; i < list.size(); i++) {
			File f = new File(list.get(i));
			if (f.exists()) {
				params.addBodyParameter(filename[i], f);
				MyLog.e("submitData" + i, list.get(i));
			}
		}
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.POST, HttpInterfaces.ORG_POST, params,
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								MyToast.show(PropertyFix.this, "提交成功",
										Toast.LENGTH_SHORT);
								deleteDir(MyApplication.cameraPath);
								finish();
							}
						} catch (JSONException e) {
							e.printStackTrace();

						}
					}
				});

	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		// 判断删除图标是否显示
		// private boolean isgShowDelete;
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		/*
		 * public void setIsShowDelete(boolean isShowDelete){
		 * this.isgShowDelete=isShowDelete; notifyDataSetChanged(); }
		 */

		public int getCount() {
			return (listDatas.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// final int coord = position;
			ViewHolder holder = null;

			System.out.println("测试下表=" + position);
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_gridview, parent,
						false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_addfixgrid);
				holder.deleteimage = (ImageView) convertView
						.findViewById(R.id.delete_markView);
				holder.image.setVisibility(View.VISIBLE);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.image.setVisibility(View.VISIBLE);
			if (position == listDatas.size()) {
				holder.image.setImageDrawable(getResources().getDrawable(
						R.drawable.icon_addpic_unfocused));
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				holder.deleteimage.setVisibility(View.GONE);
			} else {
				bitmapUtils.display(holder.image, listDatas.get(position));
				holder.deleteimage.setVisibility(View.VISIBLE);
				holder.deleteimage.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						File photofile = new File(listDatas.get(position));
						if (photofile.exists()) {
							photofile.delete();
						}
						listDatas.remove(listDatas.get(position));
						MyLog.e("hehheheeh", listDatas.size() + "");
						MyLog.e("getView", position + "");
						adapter.notifyDataSetChanged();
						// File dir = new File(MyApplication.cameraPath);
						// for(String str:dir.list()){
						// MyLog.e("hehheheeh",str);
						// }

					}
				});
			}

			if (position == 3) {
				holder.image.setVisibility(View.GONE);
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
			public ImageView deleteimage;
		}

		// Handler handler = new Handler() {
		// public void handleMessage(Message msg) {
		// switch (msg.what) {
		// case 1:
		// adapter.notifyDataSetChanged();
		// break;
		// }
		// super.handleMessage(msg);
		// }
		// };

	}

	// 删除文件
	public static void deleteDir(String path) {
		File dir = new File(path);
		if (dir == null || !dir.exists() || !dir.isDirectory())
			return;
		for (File file : dir.listFiles()) {
			if (file.isFile())
				file.delete(); // 删除所有文件
			else if (file.isDirectory())
				deleteDir(path); // 递规的方式删除文件夹
		}
		dir.delete();// 删除目录本身
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	// 获取相册所选图片路径
	@SuppressLint("NewApi")
	public String getPath(Context context, Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];
				Log.e("ssssss", "DocumentProvider");
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}
				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));
				Log.e("ssssss", "DownloadsProvider");
				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				Log.e("ssssss", "isMediaDocument");
				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			Log.e("ssssss", "content");
			// Return the remote address
			if (isGooglePhotosUri(uri)) {

				return uri.getLastPathSegment();
			}

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			Log.e("ssssss", "file");
			return uri.getPath();
		}

		return null;
	}

	public String getDataColumn(Context context, Uri uri, String selection,
			String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	public boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	public boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	public boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		deleteDir(MyApplication.cameraPath);
	}

}
